package com.roger.myHome.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.roger.myHome.domain.TbBloodSugar;
import com.roger.myHome.domain.TbUseMedicine;
import com.roger.myHome.entity.UseMedicineQryReq;
import com.roger.myHome.entity.dto.UserMedicineAddReq;
import com.roger.myHome.entity.vo.UseMedicineVo;
import com.roger.myHome.mapper.BloodSugarsMapper;
import com.roger.myHome.mapper.UseMedicineMapper;
import com.roger.myHome.page.EUDataGridResult;
import com.roger.myHome.service.UseMedicineService;
import com.roger.myHome.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UseMedicineServiceImpl implements UseMedicineService {
    @Resource
    private BloodSugarsMapper bloodSugarsMapper;

    @Resource
    private UseMedicineMapper useMedicineMapper;

    @Override
    public EUDataGridResult page(UseMedicineQryReq qryReq) {

        List<UseMedicineVo> list = useMedicineMapper.list(qryReq);

        EUDataGridResult result = new EUDataGridResult(list, useMedicineMapper.selectCount(qryReq));

        return result;
    }

    @Override
    public EUDataGridResult findByBloodSugarId(Long bloodSugarId) {
        QueryWrapper<TbBloodSugar> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("measure_time").eq("id",bloodSugarId);
        TbBloodSugar info = bloodSugarsMapper.selectList(queryWrapper).get(0);

        String useTime = info.getMeasureTime().substring(0,10);

        List<UseMedicineVo> list = useMedicineMapper.findByBloodSugar(useTime);

        UseMedicineQryReq qryReq = new UseMedicineQryReq();
        qryReq.setUseTime(useTime);

        EUDataGridResult result = new EUDataGridResult(list,useMedicineMapper.selectCount(qryReq));
        result.setTotal(useMedicineMapper.selectCount(qryReq));
        return result;
    }

    @Override
    public String add(UserMedicineAddReq req) {
        TbUseMedicine useMedicine = new TbUseMedicine();
        BeanUtils.copyProperties(req, useMedicine);
        useMedicineMapper.insert(useMedicine);
        Map hashMap = new HashMap();
        hashMap.put("result", "新增成功!");

        return StringUtils.getJSONString(hashMap);
    }

    @Override
    public String deleteById(Long id) {
        Map hashMap = new HashMap();
        useMedicineMapper.deleteById(id);
        hashMap.put("result", "删除成功!");

        return StringUtils.getJSONString(hashMap);
    }
}
